/*
 * Copyright 2013-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.order.service.impl;


import com.common.BusinessException;
import com.common.Result;
import com.common.ResultEnum;
import com.order.entity.Order;
import com.order.feign.StorageServiceFeignClient;
import com.order.feign.dto.StorageDTO;
import com.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StorageServiceFeignClient storageService;
    @Override
//    @GlobalTransactional(name="createOrder",rollbackFor=Exception.class)
    public Result<?> createOrder(String userId, String commodityCode, Integer count) {

//        logger.info("[createOrder] current XID: {}", RootContext.getXID());

        //deduct storage
        StorageDTO storageDTO = new StorageDTO();
        storageDTO.setCommodityCode(commodityCode);
        storageDTO.setCount(count);
        //openFeign远程调用
        Integer storageCode = storageService.reduceStock(storageDTO).getCode();
        if (storageCode.equals(ResultEnum.COMMON_FAILED.getCode())) {
            throw new BusinessException("stock not enough");
        }

        // deduct balance
//        int price = count * 2;
//        AccountDTO accountDTO = new AccountDTO();
//        accountDTO.setUserId(userId);
//        accountDTO.setPrice(price);
//        //RestTemplate远程调用
//        //String account_url = "http://localhost:8020/account/reduce-balance";
//        //整合了Nacos+LoadBalaner,可以使用微服务名tlmall-account代替localhost:8020
//        //String account_url = "http://tlmall-account/account/reduce-balance";
//        //Integer accountCode = restTemplate.postForObject(account_url, accountDTO, Result.class).getCode();
//        //openFeign远程调用
//        Integer accountCode = accountService.reduceBalance(accountDTO).getCode();
//        if (accountCode.equals(COMMON_FAILED.getCode())) {
//            throw new BusinessException("balance not enough");
//        }

        // save order
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        order.setMoney(2);
        order.setCreateTime(new Timestamp(System.currentTimeMillis()));
        order.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//        orderMapper.saveOrder(order);
        String sql = "INSERT INTO `orders` (user_id, commodity_code, count, money, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                order.getUserId(),
                order.getCommodityCode(),
                order.getCount(),
                order.getMoney(),
                order.getCreateTime(),
                order.getUpdateTime()
        );
        return Result.success(order);
    }
}
